﻿using System;
using System.Collections.Generic;
using System.Text;
using VMExplorer.MemoryObjects;

namespace VMExplorer
{
	class Scanner
	{
    #region Private fields

    private VMEDocument _doc;

    #endregion
    #region Construction

    public Scanner (VMEDocument doc)
    {
      _doc = doc;
    }

    #endregion
    #region Scan memory

    public IEnumerable<IMemoryObject> FindOrphans ()
    {
      List<IMemoryObject> memObjects = new List<IMemoryObject> ();

      if (NextRegion != null)
      {
        foreach (RegionInfo ri in _doc.AddressRanges)
        {
          if (ri.Usage!= RegionUsage.Free && ri.Related.Count==0)
          {
						NextRegion (this, new NextRegionEventArgs (_doc.ProcessHandle, ri, memObjects));
          }
        }
      }

      return memObjects;
    }

    public IEnumerable<IMemoryObject> Scan (RegionInfo ri)
    {
      List<IMemoryObject> memObjects = new List<IMemoryObject> ();

      if (NextRegion != null)
      {
				NextRegion (this, new NextRegionEventArgs (_doc.ProcessHandle, ri, memObjects));
      }

      return memObjects;
    }

    #endregion
    #region Events

	  public delegate void NextRegionHandler (object sender, NextRegionEventArgs e);

	  public class NextRegionEventArgs : EventArgs
    {
      #region Construction

      public NextRegionEventArgs (SafeProcessHandle hProcess, RegionInfo ri, List<IMemoryObject> memObjects)
		  {
        ProcessHandle = hProcess;
			  Range = ri;
        MemObjects = memObjects;
			  Handled = false;
      }

      #endregion
      #region Public properties

      public SafeProcessHandle ProcessHandle { get; private set; }
      public RegionInfo Range { get; private set; }
      public List<IMemoryObject> MemObjects { get; private set; }
		  public bool Handled { get; set; }

      #endregion
    }

    public event NextRegionHandler NextRegion;

    #endregion
  }


}
